<script setup>
import { ref, reactive, onMounted, nextTick, onUnmounted } from "vue";
import { ElMessage } from "element-plus";
import * as echarts from "echarts";
import {
  Search,
  RefreshRight,
  TrendCharts,
  Dish,
  Place,
  Goods,
} from "@element-plus/icons-vue";

import {
  getPurchaseCostAnalysis,
  getStallCostRatioStat,
  getGoodsCountByCategoryStat,
  getDailyTotalCostStat,
} from "../../api/costStatistics";

import { getStsloglist } from "../../api/logs";

// 档口固定颜色
const STALL_COLOR_MAP = {
  学生包餐: "#5470C6", // 蓝色
  教职工及培训部: "#91CC75", // 绿色
  包间: "#FAC858", // 黄色
};

// 档口固定排序
const STALL_ORDER = ["学生包餐", "包间", "教职工及培训部"];
const sortSeriesByStallOrder = (seriesData, includeTotal = false) => {
  const orderedSeries = [];
  const totalSeries = [];
  const otherSeries = [];

  STALL_ORDER.forEach((name) => {
    const seriesItem = seriesData.find((s) => s.name === name);
    if (seriesItem) {
      orderedSeries.push(seriesItem);
    }
  });

  seriesData.forEach((s) => {
    const isTotal = s.name.includes("总成本") || s.extend?.isTotal;

    if (isTotal) {
      totalSeries.push(s);
    } else if (!STALL_ORDER.includes(s.name)) {
      otherSeries.push(s);
    }
  });

  let finalSeries = [...orderedSeries, ...otherSeries];

  if (includeTotal) {
    finalSeries = [...finalSeries, ...totalSeries];
  }

  return finalSeries;
};

const loading = ref(false);

// 食材成本按分类分析
const purchaseCostRef = ref(null);
let purchaseCostChart = null;

// 档口成本占比分析
const stallCostRatioRef = ref(null);
let stallCostRatioChart = null;

// 采购物品分类统计
const goodsCountRef = ref(null);
let goodsCountChart = null;

// 每日总成本趋势分析
const dailyTotalCostRef = ref(null);
let dailyTotalCostChart = null;

const chartDashboardRef = ref(null);
let resizeObserver = null;

// 默认日期范围（最近 10 天）
const getDefaultDateRange = () => {
  const end = new Date();
  const start = new Date();
  start.setTime(start.getTime() - 3600 * 1000 * 24 * 9);
  return { start, end };
};

const { start, end } = getDefaultDateRange();

const searchForm = reactive({
  startDate: start,
  endDate: end,
  stallIds: null,
});

// 档口选项
const stallOptions = ref([]);

const analysisData = reactive({
  // 每日总成本趋势分析 (折线图)
  dailyTotalCost: { dates: [], series: [] },
  // 食材成本按分类分析 (分组柱状图)
  purchaseCost: { xAxisData: [], series: [], legendData: [] },
  // 档口成本占比分析 (饼图)
  stallCostRatio: { pieChartData: [], totalAmount: 0 },
  // 采购物品分类统计 (饼图, 无筛选)
  goodsCount: { pieChartData: [], totalGoodsCount: 0 },
});

// 格式化日期范围参数
const formatSearchParameters = () => {
  const startDate = searchForm.startDate;
  const endDate = searchForm.endDate;

  const formatDateString = (dateObj) => {
    if (!dateObj) return "";

    const year = dateObj.getFullYear();
    const month = String(dateObj.getMonth() + 1).padStart(2, "0");
    const day = String(dateObj.getDate()).padStart(2, "0");

    return `${year}-${month}-${day}`;
  };

  return {
    startDate: formatDateString(startDate),
    endDate: formatDateString(endDate),
    stallIds: searchForm.stallIds ? searchForm.stallIds.join(",") : "",
  };
};

// 初始化 ECharts 实例
const initializeChart = (chartRef, chartInstance) => {
  if (chartRef && chartRef.value && !chartInstance) {
    if (chartRef.value.clientWidth > 0 && chartRef.value.clientHeight > 0) {
      chartInstance = echarts.init(chartRef.value);
      return chartInstance;
    }
  }
  return chartInstance;
};

// 批量初始化所有图表实例
const initAllCharts = () => {
  purchaseCostChart = initializeChart(purchaseCostRef, purchaseCostChart);
  stallCostRatioChart = initializeChart(stallCostRatioRef, stallCostRatioChart);
  goodsCountChart = initializeChart(goodsCountRef, goodsCountChart);
  dailyTotalCostChart = initializeChart(dailyTotalCostRef, dailyTotalCostChart);

  window.removeEventListener("resize", resizeChart);
  window.addEventListener("resize", resizeChart);
};

// 分组柱状图配置
const getBarChartOptions = (data) => {
  const costDetails = data.costDetails || {};
  const { totalCost = 0, categoryRatios = [] } = data;
  // 格式化日期
  const formatTitleDate = (date) => {
    if (date instanceof Date && !isNaN(date)) {
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, "0");
      const day = String(date.getDate()).padStart(2, "0");
      return `${year}-${month}-${day}`;
    }
    return "N/A";
  };
  const startDate = formatTitleDate(searchForm.startDate);
  const endDate = formatTitleDate(searchForm.endDate);

  // 动态计算左侧 Y 轴的最大值和间隔
  let maxCost = 0;
  data.series.forEach((s) => {
    s.data.forEach((cost) => {
      maxCost = Math.max(maxCost, Number(cost) || 0);
    });
  });

  if (maxCost === 0) {
    maxCost = 100;
  }

  const paddedMax = maxCost * 1.1;

  let niceInterval = 0;
  const targetSplitNumber = 5;

  const rawInterval = paddedMax / targetSplitNumber;

  if (rawInterval < 10) {
    niceInterval = Math.ceil(rawInterval / 1) * 1;
  } else if (rawInterval < 50) {
    niceInterval = Math.ceil(rawInterval / 5) * 5;
  } else if (rawInterval < 100) {
    niceInterval = Math.ceil(rawInterval / 10) * 10;
  } else {
    niceInterval = Math.ceil(rawInterval / 100) * 100;
  }

  const leftAxisMax = niceInterval * targetSplitNumber;

  const stallNames = data.series.map((s) => s.name);

  const fixedBarColors = stallNames
    .map((name) => STALL_COLOR_MAP[name])
    .filter((color) => color);

  const barSeries = data.series.map((s) => ({
    ...s,
    type: "bar",
    barMaxWidth: 160,
    itemStyle: {
      color: STALL_COLOR_MAP[s.name] || undefined,
    },
    label: {
      show: true,
      position: "top",
      formatter: ({ value }) => {
        const numValue = Number(value);
        if (numValue > 0.01) {
          return numValue.toFixed(2);
        }
        return "";
      },
      color: "#333",
      fontSize: 13,
      fontWeight: "bold",
    },
  }));

  const ratioSeries = {
    name: "分类成本占比",
    type: "line",
    yAxisIndex: 1,
    data: categoryRatios,
    smooth: true,
    symbol: "circle",
    symbolSize: 10,
    lineStyle: {
      width: 2,
      type: "dashed",
    },
    itemStyle: { color: "#fe6895" },
    label: {
      show: false,
    },
    tooltip: {
      valueFormatter: (value) => `${Number(value).toFixed(2)}%`,
    },
  };

  const allSeries = [...barSeries, ratioSeries];

  const finalColors = [...Object.values(STALL_COLOR_MAP), "#fe6895"];

  return {
    color: finalColors,
    title: {
      text: "食材成本按分类分析",
      subtext: `分析时间: ${startDate} 至 ${endDate} (食材总成本: ${totalCost.toFixed(
        2
      )} 元)`,
      left: "center",
      subtextStyle: {
        fontWeight: "bold",
      },
    },
    tooltip: {
      trigger: "axis",

      axisPointer: { type: "shadow" },
      formatter: (params) => {
        const categoryName = params[0].name;

        let str = `<strong>${categoryName} (分类)</strong><br/>`;
        let total = 0;
        let ratio = "N/A";

        params.forEach((item) => {
          if (item.seriesName === "分类成本占比") {
            ratio = `${Number(item.value).toFixed(2)}%`;
          } else {
            total += Number(item.value);
            str +=
              item.marker +
              item.seriesName +
              `: ${Number(item.value).toFixed(2)} 元<br/>`;
          }
        });

        // 总成本、占比
        str += `<hr style="margin: 2px 0"/><strong>分类总成本: ${total.toFixed(
          2
        )} 元</strong>`;
        str += `<br/>${
          params.find((p) => p.seriesName === "分类成本占比")?.marker || "🔹"
        } <strong>成本占比: ${ratio}</strong>`;

        const categoryDetailsList = costDetails[categoryName] || [];
        const listCount = categoryDetailsList.length;
        const displayLimit = 10;

        if (listCount > 0) {
          let detailTitle = "";
          if (listCount < displayLimit) {
            detailTitle = `全部 ${listCount} 种食材成本明细:`;
          } else {
            detailTitle = `Top ${displayLimit} 食材成本明细:`;
          }
          str += `<hr style="margin: 5px 0"/><strong>✨ ${detailTitle}</strong><br/>`;

          categoryDetailsList.slice(0, displayLimit).forEach((goods, index) => {
            const markerColor =
              index === 0
                ? "red"
                : index < 3
                ? "orange"
                : index < 10
                ? "green"
                : "gray";
            str +=
              `<span style="display: inline-block; width: 10px; height: 10px; border-radius: 50%; background: ${markerColor}; margin-right: 5px;"></span>` +
              `<strong>${goods.name}</strong> (${
                goods.stall
              }): ${goods.cost.toFixed(2)} 元<br/>`;
          });
          if (categoryDetailsList.length > displayLimit) {
            str += `... (共 ${categoryDetailsList.length} 种食材)`;
          }
        } else {
          str += `<hr style="margin: 5px 0"/><em>- 暂无食材成本明细 -</em>`;
        }
        return str;
      },
    },
    legend: {
      data: data.legendData,
      bottom: 0,
      type: "scroll",
      textStyle: {
        fontSize: 14,
        fontWeight: "bold",
      },
    },
    grid: {
      left: "3%",
      right: "3%",
      bottom: "7%",
      containLabel: true,
    },
    xAxis: {
      type: "category",
      data: data.xAxisData,
      axisLabel: {
        interval: 0,
        rotate: 0,
        formatter: (value, index) => {
          const ratio = categoryRatios[index] || 0;
          let formattedValue = value;
          if (value.length > 5) {
            formattedValue = value.substring(0, 5) + "...";
          }

          if (ratio > 0) {
            return `${formattedValue}{ratio|（${ratio}%） }`;
          }
          return formattedValue;
        },
        fontSize: 14,
        fontWeight: "bold",
        rich: {
          ratio: {
            color: "#fe6895",
            fontSize: 14,
            fontWeight: "normal",
          },
        },
        margin: 20,
      },
    },
    yAxis: [
      {
        type: "value",
        name: "金额 (元)",
        axisLabel: {
          formatter: "{value} 元",
        },
        min: 0,
        max: leftAxisMax,
        interval: niceInterval,
        splitNumber: targetSplitNumber,
        nameTextStyle: {
          color: "#333",
        },
      },
      {
        type: "value",
        name: "占比 (%)",
        min: 0,
        max: 100,
        interval: 20,
        splitLine: { show: false },
        axisLabel: {
          formatter: "{value} %",
          color: "#333",
        },
        nameTextStyle: {
          color: "#333",
        },
      },
    ],
    series: allSeries,
  };
};

// 甜甜圈饼图配置
const getPieChartOptions = (
  pieData,
  titleText,
  valueName,
  showPercentage = true,
  useStallColorMap = false
) => {
  const validData = pieData.filter((item) => item.value > 0);
  const total = validData.reduce((sum, item) => sum + item.value, 0);

  let chartColors = undefined;
  if (useStallColorMap) {
    const names = validData.map((item) => item.name);
    chartColors = names
      .map((name) => STALL_COLOR_MAP[name])
      .filter((color) => color);
  }

  const unit =
    valueName.includes("金额") || valueName.includes("成本")
      ? " 元"
      : " 个商品";

  const formattedTotal =
    valueName.includes("金额") || valueName.includes("成本")
      ? total.toFixed(2)
      : Math.floor(total);

  return {
    ...(chartColors && chartColors.length > 0 ? { color: chartColors } : {}),
    title: {
      text: titleText,
      subtext: `总${valueName}：${formattedTotal}${unit}`,
      left: "center",
      subtextStyle: {
        fontWeight: "bold",
      },
    },
    tooltip: {
      trigger: "item",
      formatter: (params) => {
        const valueStr =
          valueName.includes("金额") || valueName.includes("成本")
            ? params.value.toFixed(2)
            : Math.floor(params.value);
        return `${params.name}<br/>${valueName}: ${valueStr}${unit} (${params.percent}%)`;
      },
    },
    legend: {
      data: validData.map((item) => item.name),
      orient: "vertical",
      left: "left",
      type: "scroll",
      maxHeight: "90%",
      textStyle: {
        fontSize: 14,
        fontWeight: "bold",
      },
    },
    series: [
      {
        name: valueName,
        type: "pie",
        radius: ["30%", "62%"],
        center: ["53%", "55%"],
        data: validData,
        itemStyle: {
          borderRadius: 5,
          borderColor: "#fff",
          borderWidth: 2,
        },
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: "rgba(0, 0, 0, 0.5)",
          },
        },
        label: {
          show: true,
          position: "outside",
          fontSize: 13,
          fontWeight: "bold",
          formatter: (params) => {
            const valueStr =
              valueName.includes("金额") || valueName.includes("成本")
                ? params.value.toFixed(2)
                : Math.floor(params.value);

            let result = `${params.name}：\n ${valueStr}${unit}`;
            if (showPercentage) {
              result += ` (${params.percent}%)`;
            }
            return result;
          },
        },
        labelLine: {
          show: true,
          length: 15,
          length2: 5,
        },
      },
    ],
  };
};

// 折线图配置
const getLineChartOptions = (data) => {
  const { dates, series } = data;
  const formatTitleDate = (date) => {
    if (date instanceof Date && !isNaN(date)) {
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, "0");
      const day = String(date.getDate()).padStart(2, "0");
      return `${year}-${month}-${day}`;
    }
    return "N/A";
  };
  const startDate = formatTitleDate(searchForm.startDate);
  const endDate = formatTitleDate(searchForm.endDate);

  const legendData = series.map((s) => s.name);

  // 根据日期字符串返回周几
  const getDayOfWeek = (dateString) => {
    const date = new Date(dateString);
    if (isNaN(date.getTime())) return "";
    const days = ["日", "一", "二", "三", "四", "五", "六"];
    return `周${days[date.getDay()]}`;
  };

  const chartColors = legendData
    .map((name) => {
      const isTotal =
        name.includes("总成本") ||
        series.find((s) => s.name === name)?.extend?.isTotal;
      if (isTotal) {
        return "#F56C6C"; // 总成本红色
      }
      return STALL_COLOR_MAP[name] || null;
    })
    .filter((color) => color !== null);

  const lineSeries = series.map((s) => {
    const isTotal = s.extend?.isTotal || false;
    return {
      ...s,
      type: "line",
      smooth: true,
      symbol: "circle",
      symbolSize: isTotal ? 10 : 6,
      itemStyle: {
        color: isTotal ? "#F56C6C" : STALL_COLOR_MAP[s.name] || undefined,
      },
      lineStyle: {
        width: isTotal ? 3 : 2,
        type: isTotal ? "solid" : "dashed",
      },
    };
  });

  return {
    color: chartColors,
    title: {
      text: "每日食材总成本及各档口食材成本趋势分析",
      subtext: `分析时间: ${startDate} 至 ${endDate}`,
      left: "center",
      subtextStyle: {
        fontWeight: "bold",
      },
    },
    tooltip: {
      trigger: "axis",
      formatter: (params) => {
        const dateName = params[0].name;
        const dayOfWeek = getDayOfWeek(dateName);
        let str = `<strong>日期: ${dateName} (${dayOfWeek})</strong><br/>`;
        params.forEach((item) => {
          str += `${item.marker} ${item.seriesName}: <strong>${Number(
            item.value
          ).toFixed(2)}</strong> 元<br/>`;
        });
        return str;
      },
    },
    legend: {
      data: legendData,
      bottom: 0,
      type: "scroll",
      textStyle: {
        fontSize: 14,
        fontWeight: "bold",
      },
    },
    grid: { left: "3%", right: "3%", bottom: "7%", containLabel: true },
    xAxis: {
      type: "category",
      boundaryGap: false,
      data: dates,
      axisLabel: {
        rotate: 30,
        margin: 20,
        fontWeight: "bold",
      },
    },
    yAxis: {
      type: "value",
      name: "金额 (元)",
      axisLabel: { formatter: "{value} 元" },
      min: 0,
    },
    series: lineSeries,
  };
};

// 按分类和档口统计出库总金额
async function loadPurchaseCostAnalysis(params) {
  try {
    const res = await getPurchaseCostAnalysis(params);
    if (res.code === 0 && res.data) {
      const { xAxisData, series, costDetails } = res.data;

      const sortedSeries = sortSeriesByStallOrder(series, false);

      // 分类总成本
      let totalCost = 0;
      const categoryTotals = new Array(xAxisData.length).fill(0);

      sortedSeries.forEach((s) => {
        s.data.forEach((cost, index) => {
          const value = Number(cost) || 0;
          categoryTotals[index] += value;
          totalCost += value;
        });
      });

      // 每个分类成本占比
      const categoryRatios = categoryTotals.map((total) =>
        totalCost > 0 ? ((total / totalCost) * 100).toFixed(2) : 0
      );

      analysisData.purchaseCost.xAxisData = xAxisData || [];
      analysisData.purchaseCost.series = sortedSeries || [];
      analysisData.purchaseCost.costDetails = costDetails || {};

      analysisData.purchaseCost.totalCost = totalCost;
      analysisData.purchaseCost.categoryRatios = categoryRatios;
      analysisData.purchaseCost.legendData = [
        ...sortedSeries.map((s) => s.name),
        "分类成本占比",
      ];

      if (purchaseCostChart) {
        purchaseCostChart.setOption(
          getBarChartOptions(analysisData.purchaseCost),
          true
        );
      }
    } else {
      console.error("获取食材成本分析数据失败:", res.msg);
      ElMessage.error(`食材成本分析失败: ${res.msg}`);
    }
  } catch (error) {
    console.error("加载食材成本分析数据失败:", error);
  }
}

//  按档口成本占比
async function loadStallCostRatioStat(params) {
  try {
    const res = await getStallCostRatioStat(params);
    if (res.code === 0 && res.data) {
      let rawData = res.data.pieChartData || [];

      const tempSeries = rawData.map((item) => ({
        name: item.name,
        value: item.value,
        data: [item.value],
      }));

      const sortedSeries = sortSeriesByStallOrder(tempSeries, false);

      analysisData.stallCostRatio.pieChartData = sortedSeries.map((s) => ({
        name: s.name,
        value: s.value || s.data[0],
      }));

      analysisData.stallCostRatio.totalAmount =
        analysisData.stallCostRatio.pieChartData.reduce(
          (sum, item) => sum + item.value,
          0
        );

      if (stallCostRatioChart) {
        stallCostRatioChart.setOption(
          getPieChartOptions(
            analysisData.stallCostRatio.pieChartData,
            "档口食材成本占比分析",
            "食材成本金额",
            true,
            true
          ),
          true
        );
      }
    } else {
      console.error("获取档口食材成本占比数据失败:", res.msg);
      ElMessage.error(`档口食材成本占比分析失败: ${res.msg}`);
    }
  } catch (error) {
    console.error("加载档口食材成本占比数据失败:", error);
  }
}

// 按分类统计食材种类数量
async function loadGoodsCountByCategoryStat() {
  try {
    const res = await getGoodsCountByCategoryStat();

    if (res.code === 0 && res.data) {
      analysisData.goodsCount.pieChartData = res.data.pieChartData || [];
      analysisData.goodsCount.totalGoodsCount =
        analysisData.goodsCount.pieChartData.reduce(
          (sum, item) => sum + item.value,
          0
        );

      if (goodsCountChart) {
        goodsCountChart.setOption(
          getPieChartOptions(
            analysisData.goodsCount.pieChartData,
            "采购物品分类统计",
            "数量",
            false,
            false
          ),
          true
        );
      }
    } else {
      console.error("获取食材种类统计数据失败:", res.msg);
      ElMessage.error(`食材种类统计失败: ${res.msg}`);
    }
  } catch (error) {
    console.error("加载食材种类统计数据失败:", error);
  }
}

// 按日期统计每日总成本
async function loadDailyTotalCostStat(params) {
  try {
    const res = await getDailyTotalCostStat(params);
    if (res.code === 0 && res.data) {
      const { dates, series } = res.data;

      const sortedSeries = sortSeriesByStallOrder(series, true);
      analysisData.dailyTotalCost.dates = dates || [];
      analysisData.dailyTotalCost.series = sortedSeries || [];

      if (dailyTotalCostChart) {
        dailyTotalCostChart.setOption(
          getLineChartOptions(analysisData.dailyTotalCost),
          true
        );
      }
    } else {
      console.error("获取每日食材总成本趋势数据失败:", res.msg);
      ElMessage.error(`每日食材总成本趋势分析失败: ${res.msg}`);
    }
  } catch (error) {
    console.error("加载每日总成本趋势数据失败:", error);
  }
}
// 加载所有图表数据
async function loadAllCharts() {
  loading.value = true;
  try {
    const filteredParams = formatSearchParameters();

    const loadPromises = [
      loadPurchaseCostAnalysis(filteredParams),
      loadStallCostRatioStat(filteredParams),
      loadGoodsCountByCategoryStat(),
      loadDailyTotalCostStat(filteredParams),
    ];

    await Promise.allSettled(loadPromises);
  } catch (error) {
    console.error("加载图表数据失败:", error);
    ElMessage.error("批量加载图表数据失败，请检查网络或服务");
  } finally {
    loading.value = false;
  }
}

// 快捷日期选择
const handleQuickSelect = (days) => {
  const end = new Date();
  const start = new Date();
  start.setTime(end.getTime() - 3600 * 1000 * 24 * (days - 1));

  searchForm.endDate = end;
  searchForm.startDate = start;
  handleSearch();
};

const handleSearch = () => {
  // 检查日期合法性
  if (
    searchForm.startDate &&
    searchForm.endDate &&
    searchForm.startDate > searchForm.endDate
  ) {
    ElMessage.warning("开始日期不能晚于结束日期！");
    return;
  }
  initAllCharts();
  loadAllCharts();
};

const handleReset = () => {
  const { start, end } = getDefaultDateRange();
  searchForm.startDate = start;
  searchForm.endDate = end;
  searchForm.stallIds = null;
  handleSearch();
};

// 图表重绘
const resizeChart = () => {
  purchaseCostChart?.resize();
  stallCostRatioChart?.resize();
  goodsCountChart?.resize();
  dailyTotalCostChart?.resize();
};

// 初始化 ResizeObserver
const initResizeObserver = () => {
  if (window.ResizeObserver && chartDashboardRef.value) {
    resizeObserver = new ResizeObserver(() => {
      nextTick(() => {
        setTimeout(() => {
          resizeChart();
        }, 300);
      });
    });
    resizeObserver.observe(chartDashboardRef.value);
  } else {
    console.warn(
      "当前环境不支持 ResizeObserver API，图表可能无法自动适应侧边栏变化。"
    );
  }
};
// 加载档口选项
async function loadStallOptions() {
  try {
    const res = await getStsloglist({
      page: 1,
      pageSize: 9999,
      status: 1,
    });

    if (
      res.code === 0 &&
      res.data &&
      Array.isArray(res.data.list) &&
      res.data.list.length > 0
    ) {
      const rawStalls = Array.isArray(res.data.list[0])
        ? res.data.list[0]
        : Object.values(res.data.list[0] || {});

      stallOptions.value = rawStalls
        .filter(
          (stall) =>
            (stall.stall_id || stall.id) && (stall.name || stall.stall_name)
        )
        .map((stall) => ({
          value: stall.stall_id || stall.id,
          label: stall.name || stall.stall_name,
        }));
    }
  } catch (error) {
    console.error("加载档口列表失败:", error);
  }
}

onMounted(() => {
  nextTick(() => {
    initAllCharts();
    initResizeObserver();
    loadStallOptions();
    loadAllCharts();
  });
});

onUnmounted(() => {
  if (resizeObserver) {
    resizeObserver.disconnect();
    resizeObserver = null;
    // 清除全局 resize 监听，防止内存泄漏
    window.removeEventListener("resize", resizeChart);
  }
});
</script>

<template>
  <div class="cost-analysis-container">
    <el-card class="main-card" shadow="never">
      <div class="card-header">
        <h3>
          <el-icon style="color: black"><TrendCharts /></el-icon>成本统计
        </h3>
        <span />
      </div>
      <el-form :inline="true" :model="searchForm" class="filter-form-inline">
        <el-row :gutter="20">
          <el-col :span="4">
            <el-form-item label="开始日期">
              <el-date-picker
                v-model="searchForm.startDate"
                type="date"
                placeholder="选择开始日期"
                style="width: 100%"
                :disabled="loading"
              />
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item label="结束日期">
              <el-date-picker
                v-model="searchForm.endDate"
                type="date"
                placeholder="选择结束日期"
                style="width: 100%"
                :disabled="loading"
              />
            </el-form-item>
          </el-col>
          <el-col :span="5.5">
            <el-button
              @click="handleQuickSelect(7)"
              size="default"
              :disabled="loading"
              >最近一周</el-button
            >
            <el-button
              @click="handleQuickSelect(15)"
              size="default"
              :disabled="loading"
              >最近半月</el-button
            >
            <el-button
              @click="handleQuickSelect(30)"
              size="default"
              :disabled="loading"
              >最近一月</el-button
            >
          </el-col>
          <el-col :span="5">
            <el-form-item label="按档口">
              <el-select
                v-model="searchForm.stallIds"
                placeholder="选择档口 (可多选)"
                clearable
                multiple
                filterable
                collapse-tags
                collapse-tags-tooltip
                style="width: 100%"
                :disabled="loading"
              >
                <el-option
                  v-for="item in stallOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="5" class="action-buttons-col">
            <el-form-item>
              <el-button
                type="primary"
                :icon="Search"
                @click="handleSearch"
                :loading="loading"
                >查询</el-button
              >
              <el-button
                @click="handleReset"
                :icon="RefreshRight"
                :disabled="loading"
                >重置</el-button
              >
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div
        class="chart-dashboard-grid"
        v-loading="loading"
        element-loading-text="正在加载所有图表数据..."
        ref="chartDashboardRef"
      >
        <el-card shadow="hover" class="chart-card full-width">
          <template #header>
            <div class="chart-title-header">
              <el-icon style="color: #409eff"><TrendCharts /></el-icon
              ><span>每日食材总成本及各档口食材成本趋势分析</span>
            </div>
          </template>
          <div ref="dailyTotalCostRef" class="chart-container-lg" />
        </el-card>

        <el-card shadow="hover" class="chart-card full-width">
          <template #header>
            <div class="chart-title-header">
              <el-icon><Dish /></el-icon><span>食材成本按分类分析</span>
            </div>
          </template>
          <div ref="purchaseCostRef" class="chart-container-lg" />
        </el-card>
        <el-card shadow="hover" class="chart-card half-width">
          <template #header>
            <div class="chart-title-header">
              <el-icon><Place /></el-icon><span>档口食材成本占比分析</span>
            </div>
          </template>
          <div ref="stallCostRatioRef" class="chart-container-sm" />
        </el-card>
        <el-card shadow="hover" class="chart-card half-width">
          <template #header>
            <div class="chart-title-header">
              <el-icon><Goods /></el-icon>
              <span>采购物品分类统计</span>
              <span style="margin-left: 30px; font-size: 15px; color: #86878c"
                >此图表不随上方筛选条件变化。</span
              >
            </div>
          </template>
          <div ref="goodsCountRef" class="chart-container-sm"
        /></el-card>
      </div>
      <div class="pagination-container pagination-split">
        <span class="pagination-info"
          >当前查询范围：{{
            searchForm.startDate?.toLocaleDateString("zh-CN") || "N/A"
          }}至{{
            searchForm.endDate?.toLocaleDateString("zh-CN") || "N/A"
          }}</span
        >
      </div>
    </el-card>
  </div>
</template>

<style scoped lang="less">
.cost-analysis-container {
  min-height: 100vh;
}

.main-card {
  background: #ffffff;
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
  box-sizing: border-box;

  :deep(.el-card__body) {
    padding: 0px 15px 15px 15px;
  }
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 18px;
  border-bottom: 1px solid rgb(217, 217, 217);

  h3 {
    display: flex;
    align-items: center;
    font-size: 18px;
    font-weight: 600;
    color: rgb(38, 38, 38);
    .el-icon {
      margin-right: 8px;
      font-size: 18px;
      color: rgb(27, 130, 241);
    }
  }
}

.filter-form-inline {
  // margin-bottom: 20px;
  padding: 10px 0;
  .el-form-item {
    margin-right: 0;
    width: 100%;
    margin-bottom: 15px;
  }
  .action-buttons-col {
    display: flex;
    align-items: flex-start;
    padding-bottom: 0;
    .el-button {
      margin-left: 10px;
      &:first-child {
        margin-left: 0;
      }
    }
  }
}

.chart-dashboard-grid {
  display: flex;
  flex-wrap: wrap;
  gap: 15px;
  padding-top: 10px;
  transition: width 0.3s, margin-left 0.3s;
}

.chart-card {
  border-radius: 8px;
  transition: transform 0.3s, box-shadow 0.3s;

  .chart-title-header {
    display: flex;
    align-items: center;
    font-size: 16px;
    font-weight: 600;
    color: #333;
    .el-icon {
      margin-right: 5px;
      color: #007bff;
    }
  }
}

.full-width {
  width: 100%;
}

.half-width {
  flex: 1 1 calc(50% - 7.5px);
  min-width: 400px;
}

.chart-container-lg {
  width: 100%;
  min-height: 550px;
}

.chart-container-sm {
  width: 100%;
  min-height: 450px;
}

.pagination-split {
  margin-top: 25px;
  flex-shrink: 0;
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-top: 1px dashed #d9d9d9;
  padding-top: 15px;

  .pagination-info {
    color: #595959;
    font-size: 14px;
    line-height: 28px;
  }
}
</style>
